package com.police.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import com.police.R;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.webkit.URLUtil;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

/**  
 * Android AutoUpdate.  
 *   
 * lazybone/2010.08.20  
 *   
 * 1.Set apkUrl.  
 *   
 * 2.check().  
 *   
 * 3.add delFile() method in resume()\onPause().  
 */  
public class UpdateAPK {   
    public Activity activity = null;   
    public int versionCode = 0;   
    public String versionName = "";   
    private static final String TAG = "AutoUpdate";    
    private String currentTempFilePath = "";   
    private String fileEx = "";   
    private String fileNa = "";   
    public String strURL;
    private ProgressDialog dialog;  
    Button tv;
    ProgressBar pb;
    TextView num;
    long length;
    long totalLength;

	String cacheFilePath;	
    public UpdateAPK(Activity activity,String strURL) {   
        this.activity = activity;  
        pb = (ProgressBar)activity.findViewById(R.id.progress);
        num = (TextView)activity.findViewById(R.id.progressNum);
        this.strURL = strURL;
        this.cacheFilePath = Environment.getExternalStorageDirectory() + "/police/apk/";
        //getCurrentVersion();   
    }   

    final Handler handler = new Handler(){
    	@Override
    	public void handleMessage(Message msg) {
    		// TODO Auto-generated method stub
    		if (msg.what == 1) {
    			pb.setProgress((int)(length*100/totalLength));
    			num.setText((length*100/totalLength)+"%  "+String.format("%1$04.2f", length/1024F)+"KB/"+String.format("%1$04.2f", totalLength/1024F)+"KB");
			}else if(msg.what == 2){
				if(activity.isFinishing() == false){
					tipsDialog();
            	}
			}
    	}
    };
    public void check() {   
        if (isNetworkAvailable(this.activity) == false) {   
            return;   
        }   
        /*if (true) {// Check version.   
            showUpdateDialog();   
        } */ 
        downloadTheFile(strURL); 
    }   
    public static boolean isNetworkAvailable(Context ctx) {   
        try {   
            ConnectivityManager cm = (ConnectivityManager) ctx   
                    .getSystemService(Context.CONNECTIVITY_SERVICE);   
            NetworkInfo info = cm.getActiveNetworkInfo();   
            return (info != null && info.isConnected());   
        } catch (Exception e) {   
            e.printStackTrace();   
            return false;   
        }   
    }   
    public void showUpdateDialog() {   
        @SuppressWarnings("unused")   
        AlertDialog alert = new AlertDialog.Builder(this.activity)   
                .setTitle("Title")   
                .setIcon(R.drawable.icon)   
                .setMessage("Update or not?")   
                .setPositiveButton("Update",   
                        new DialogInterface.OnClickListener() {   
                            public void onClick(DialogInterface dialog,   
                                    int which) {   
                                downloadTheFile(strURL);   
                                //showWaitDialog();   
                            }   
                        })   
                .setNegativeButton("Cancel",   
                        new DialogInterface.OnClickListener() {   
                            public void onClick(DialogInterface dialog,   
                                    int which) {   
                                dialog.cancel();   
                            }   
                        }).show();   
    }  
    
    //提示对话框
    public void tipsDialog(){
    	 AlertDialog alert = new AlertDialog.Builder(this.activity)   
         .setTitle("聚美提示")   
         .setMessage("下载安装包异常？")   
         .setPositiveButton("确定",   
                 new DialogInterface.OnClickListener() {   
                     public void onClick(DialogInterface dialog,   
                             int which) {   
                    	  activity.finish(); 
                     }   
                 }).show();   
    }
    
    
    
    public void showWaitDialog() {   
        dialog = new ProgressDialog(activity);   
        dialog.setMessage("Waitting for update...");   
        dialog.setIndeterminate(true);   
        dialog.setCancelable(true);   
        dialog.show();   
    }   
    public void getCurrentVersion() {   
        try {   
            PackageInfo info = activity.getPackageManager().getPackageInfo(   
                    activity.getPackageName(), 0);   
            this.versionCode = info.versionCode;   
            this.versionName = info.versionName;   
        } catch (NameNotFoundException e) {   
            e.printStackTrace();   
        }   
    }   
    private void downloadTheFile(final String strPath) {   
        fileEx = strURL.substring(strURL.lastIndexOf(".") + 1, strURL.length())   
                .toLowerCase();   
        fileNa = strURL.substring(strURL.lastIndexOf("/") + 1,   
        		strURL.length());   
//        System.out.println("   ===================downloadTheFile=================   ");
        try {   
        	new Thread(new Runnable() {   
                public void run() {   
                    try {   
                       deleteAllFiles(cacheFilePath);
//                        System.out.println("   ===================try=================   ");
                        doDownloadTheFile(strPath);   
                    } catch (Exception e) {   
//                    	System.out.println("   ===================catch=================   ");
                    	if(activity.isFinishing() == false){
                    		handler.sendEmptyMessage(2);
                    	}
                    	
                        Log.e(TAG, e.getMessage(), e);   
                    }   
                }   
            }).start();   
        } catch (Exception e) {   
            e.printStackTrace(); 
            activity.finish();    
        }   
//        System.out.println("111111111112222222222222222222222222");
    }   
    private void doDownloadTheFile(String strPath) throws Exception {   
        if (!URLUtil.isNetworkUrl(strPath)) {    
            activity.finish();
        } else {   
//        	System.out.println("doDownloadTheFile   ***********");
            URL myURL = new URL(strPath);   
            URLConnection conn = myURL.openConnection();   
            conn.setDoInput(true);
            conn.connect();   
            InputStream is = conn.getInputStream(); 
            totalLength = conn.getContentLength();
            if(totalLength<0){
            	totalLength=1887437;
            }
            if (is == null) {   
//            	System.out.println("======================stream is null===========================");
                throw new RuntimeException("stream is null");   
            }   
            File path = new File(cacheFilePath);
            if(!path.exists()){
            	path.mkdirs();
     		}
            File myTempFile = new File(cacheFilePath+fileNa);   
            currentTempFilePath = myTempFile.getAbsolutePath();   
            FileOutputStream fos = new FileOutputStream(myTempFile);   
            byte buf[] = new byte[1024];   
            do {   
//            	System.out.println("          do*********************");
                int numread = is.read(buf);   
                if (numread <= 0) {   
                    break;   
                }   
                fos.write(buf, 0, numread); 
                length = myTempFile.length();
    			handler.sendMessage(handler.obtainMessage(1));
            } while (true);   
            //dialog.cancel();   
            //dialog.dismiss();   
            openFile(myTempFile);   
            try {   
                is.close();   
//                System.out.println("0000000000999999999   ");
            } catch (Exception ex) {   
//            	System.out.println("333333333333333333333   Exception");
//                Log.e(TAG, "getDataSource() error: " + ex.getMessage(), ex); 
            }   
        }   
    }   
    private void openFile(File f) {   
        Intent intent = new Intent();   
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);   
        intent.setAction(android.content.Intent.ACTION_VIEW);   
        String type = getMIMEType(f);   
        intent.putExtra("loadapk", "loadapk");
        intent.setDataAndType(Uri.fromFile(f), type);   
        activity.startActivity(intent); 
//    	System.out.println("*************************8888888888888888888888");
        activity.finish();  
    }   
    public void delFile() {      
        File myFile = new File(currentTempFilePath);   
        if (myFile.exists()) {   
            myFile.delete();   
        }   
    }   
    private String getMIMEType(File f) {   
        /*String type = "";   
        String fName = f.getName();   
        String end = fName   
                .substring(fName.lastIndexOf(".") + 1, fName.length())   
                .toLowerCase();   
        if (end.equals("m4a") || end.equals("mp3") || end.equals("mid")   
                || end.equals("xmf") || end.equals("ogg") || end.equals("wav")) {   
            type = "audio";   
        } else if (end.equals("3gp") || end.equals("mp4")) {   
            type = "video";   
        } else if (end.equals("jpg") || end.equals("gif") || end.equals("png")   
                || end.equals("jpeg") || end.equals("bmp")) {   
            type = "image";   
        } else if (end.equals("apk")) {   
            type = "application/vnd.android.package-archive";   
        } else {   
            type = "*";   
        }   
        if (end.equals("apk")) {   
        } else {   
            type += "/*";   
        }   
        return type; */  
    	return "application/vnd.android.package-archive";
    }   
    
    

	/**
	 * 删除指定路径的文件
	 * 
	 */
	public static void deleteAllFiles(String fileName) {
		File file = new File(fileName);
		if (!file.exists()) {
			return;
		}

		if (file.isDirectory()) {
			File[] files = file.listFiles();
			int len = 0;
			if (files != null) {
				for (int i = 0; i < files.length; i++) {
					deleteAllFiles(files[i].getPath());

				}
			}
		} else {
			file.deleteOnExit();
		}

	}
}  